# -*- coding: utf-8 -*-
import datetime
import json
import random

from service.ssoService import SSOService
from util import httpUtil, configJsonUtil, aesUtil
from util.loggerFactory import Logger

logger = Logger()


class WorkHour:

    def __init__(self, xmbh, xmmc, rwbh, rwmc, gs='8', nr='日常工作'):
        self.nr = nr
        self.gs = gs
        self.rwmc = rwmc
        self.rwbh = rwbh
        self.xmmc = xmmc
        self.xmbh = xmbh
        self.fid = ''
        self.shzt = '0'


class WorkHourService:

    def __init__(self, user_id=None, user_name=None, password=None):
        self.account = configJsonUtil.get_config()['account']
        if user_id is None:
            self.user_id = self.account['user_id']
        else:
            self.user_id = user_id
        if user_name is None:
            self.user_name = self.account['user_name']
        else:
            self.user_name = user_name
        if password is None:
            self.password = aesUtil.PrpCrypt.decrypt_password(self.account['user_id'], self.account['password'])
        else:
            self.password = password
        self.sso_service = SSOService(self.user_id, self.password)
        self.app_session_key = configJsonUtil.get_config()['base']['app_session_key']
        self.mod_auth_cas = self.sso_service.get_app_session_id()[self.app_session_key]

    def fill_work_hour_random(self, day=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d'),
                              work_hour=None):
        # 默认获取当前时间
        if work_hour is None:
            programs = configJsonUtil.get_config()['programs']
            # 计算权重
            new_ps = []
            for p in programs:
                weight = p['weight']
                for w in range(int(weight)):
                    new_ps.append(p)
            # 从权重列表中选择一个项目
            pr = random.choice(new_ps)
            work_hour = {
                "xmbh": pr['xmbh'],
                "xmmc": pr['xmmc'],
                "rwbh": pr['rwbh'],
                "rwmc": pr['rwmc'],
                "gs": str(pr['gs']),
                "nr": pr['nr'],
                "fid": '',
                "shzt": '0'
            }
        self.fill_work_hour(day, work_hour)

    def fill_work_hour(self, day=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d'), work_hour_dict=None):
        logger.debug("填报工时")
        data = {"wid": "", "rq": day, "ygbh": self.user_id, "ygxm": self.user_name,
                "SJY": "PC", "xmGsList": [
                work_hour_dict]}
        data_str = json.dumps(data, ensure_ascii=False)
        response = httpUtil.send_post_request(
            "http://my.wisedu.com/jygl2/sys/gsxt/api/updateGs.do?"
            "data={}".format(data_str), cookies={self.app_session_key: self.mod_auth_cas})
        logger.debug(response.text)
        ret = json.loads(response.text, encoding='utf-8')
        if ret['status'] == 200:
            logger.debug("工时填报成功")
        else:
            logger.debug("工时填报失败")
        return ret

    def query_work_hour(self):
        logger.debug("查询我的工时")
        response = httpUtil.send_post_request(
            "http://my.wisedu.com/jygl2/sys/gsxt/modules/wdgs/V_GS_MYGS_QUERY.do",
            "YGBH={}&querySetting={}&pageSize=3&pageNumber=1".format(self.user_id,
                                                                     '[{"name":"YGBH","value":"' + self.user_id + '","linkOpt":"AND","builder":"equal"}]'),
            cookies={self.app_session_key: self.mod_auth_cas})
        logger.debug(response.text)
        logger.debug("结束查询我的工时")
        return json.loads(response.text, encoding='utf-8')

    def audit_work_hour(self):
        """审核工时"""
        logger.debug("审核工时")
        page_size = 10
        page_number = 1
        size = self.get_need_audit_hours_size()
        if size > 0:
            count = (size // page_size) + 1
            for c in range(count):
                self._audit_work_hour(page_size, page_number)
        logger.debug("结束审核工时")

    def get_need_audit_hours_size(self):
        logger.debug("查询待审核工时个数")
        response = self._list_need_audit_work_hour(1, 1)
        if response.status_code == 200:
            ret = json.loads(response.text, encoding='utf-8')
            wddb_ = ret['datas']['wddb']
            size_ = wddb_['totalSize']
            logger.debug("totalSize:{}".format(size_))
            return size_
        raise OSError('接口异常:' + response.text)

    def _list_need_audit_work_hour(self, page_size=10, page_number=1):
        params = {
            "SHR": '%' + self.user_id + '%',
            "querySetting": '[{"name":"SHR","value":"%' + self.user_id + '%","linkOpt":"AND","builder":"equal"}]',
            "pageSize": page_size,
            "pageNumber": page_number
        }
        return httpUtil.send_post_request(
            "http://my.wisedu.com/jygl2/sys/gsxt/modules/wddb/wddb.do", params,
            cookies={self.app_session_key: self.mod_auth_cas})

    def _audit_work_hour(self, page_size=10, page_number=1):
        logger.debug("查询待审核工时 page_size：{}，page_size：{}".format(page_size, page_number))
        response = self._list_need_audit_work_hour(page_size, page_number)
        if response.status_code == 200:
            ret = json.loads(response.text, encoding='utf-8')
            wddb_ = ret['datas']['wddb']
            wait_audit_hours = wddb_['rows']
            wids = list(map(lambda wait_audit_hour: wait_audit_hour['WID'], wait_audit_hours))
            if len(wids) == 0:
                logger.debug("待审核工单长度为0")
                return
            wids_str = ",".join(wids)
            data = '{"wid":"' + wids_str + '","ygbh":"01116284","shjg":"Y","shyj":""}'
            response1 = httpUtil.send_post_request(
                "http://my.wisedu.com/jygl2/sys/gsxt/api/auditGs.do",
                "data={}".format(data), cookies={self.app_session_key: self.mod_auth_cas})
            if response1.status_code == 200:
                ret1 = json.loads(response1.text, encoding='utf-8')
                if ret1['status'] == 200:
                    logger.debug("工时审核成功")
                else:
                    logger.debug("工时审核失败")
                return
